import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {
  vehicleApi,
  fuelRecordApi,
  fuelStatsApi,
} from "@/services/vehicleService";
import type {
  VehicleResponse,
  VehicleCreate,
  VehicleUpdate,
  VehicleListParams,
  VehicleFuelRecordResponse,
  VehicleFuelRecordCreate,
  VehicleFuelRecordUpdate,
  VehicleFuelRecordListParams,
  VehicleWithFuelStats,
  FuelConsumptionStats,
  FuelConsumptionStatsParams,
} from "@/types/vehicle";

export const useVehicleStore = defineStore("vehicle", () => {
  // 车辆状态
  const vehicles = ref<VehicleResponse[]>([]);
  const vehiclesWithStats = ref<VehicleWithFuelStats[]>([]);
  const currentVehicle = ref<VehicleResponse | null>(null);

  // 油耗记录状态
  const fuelRecords = ref<VehicleFuelRecordResponse[]>([]);
  const currentFuelRecord = ref<VehicleFuelRecordResponse | null>(null);

  // 统计状态
  const fuelStats = ref<FuelConsumptionStats | null>(null);

  // 通用状态
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 计算属性
  const activeVehicles = computed(() =>
    vehicles.value.filter((vehicle) => vehicle.is_active),
  );

  const vehicleCount = computed(() => vehicles.value.length);
  const activeVehicleCount = computed(() => activeVehicles.value.length);

  const totalFuelCost = computed(() =>
    fuelRecords.value.reduce((sum, record) => sum + record.fuel_cost, 0),
  );

  const totalFuelAmount = computed(() =>
    fuelRecords.value.reduce((sum, record) => sum + record.fuel_amount, 0),
  );

  // 车辆管理方法
  async function fetchVehicles(params?: VehicleListParams) {
    try {
      loading.value = true;
      error.value = null;
      const response = await vehicleApi.getVehicles(params);
      vehicles.value = response.vehicles;
      return response;
    } catch (err) {
      console.error("获取车辆列表失败:", err);
      error.value = "获取车辆列表失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchVehiclesWithStats() {
    try {
      loading.value = true;
      error.value = null;
      vehiclesWithStats.value = await vehicleApi.getVehiclesWithStats();
      return vehiclesWithStats.value;
    } catch (err) {
      console.error("获取车辆统计列表失败:", err);
      error.value = "获取车辆统计列表失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchVehicle(vehicleId: number) {
    try {
      loading.value = true;
      error.value = null;
      const vehicle = await vehicleApi.getVehicle(vehicleId);
      currentVehicle.value = vehicle;
      return vehicle;
    } catch (err) {
      console.error("获取车辆详情失败:", err);
      error.value = "获取车辆详情失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createVehicle(vehicleData: VehicleCreate) {
    try {
      loading.value = true;
      error.value = null;
      const newVehicle = await vehicleApi.createVehicle(vehicleData);
      vehicles.value.push(newVehicle);
      return newVehicle;
    } catch (err) {
      console.error("创建车辆失败:", err);
      error.value = "创建车辆失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateVehicle(vehicleId: number, vehicleData: VehicleUpdate) {
    try {
      loading.value = true;
      error.value = null;
      const updatedVehicle = await vehicleApi.updateVehicle(
        vehicleId,
        vehicleData,
      );
      const index = vehicles.value.findIndex((v) => v.id === vehicleId);
      if (index !== -1) {
        vehicles.value[index] = updatedVehicle;
      }
      if (currentVehicle.value?.id === vehicleId) {
        currentVehicle.value = updatedVehicle;
      }
      return updatedVehicle;
    } catch (err) {
      console.error("更新车辆失败:", err);
      error.value = "更新车辆失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function deleteVehicle(vehicleId: number) {
    try {
      loading.value = true;
      error.value = null;
      await vehicleApi.deleteVehicle(vehicleId);
      vehicles.value = vehicles.value.filter((v) => v.id !== vehicleId);
      if (currentVehicle.value?.id === vehicleId) {
        currentVehicle.value = null;
      }
    } catch (err) {
      console.error("删除车辆失败:", err);
      error.value = "删除车辆失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 油耗记录管理方法
  async function fetchFuelRecords(params?: VehicleFuelRecordListParams) {
    try {
      loading.value = true;
      error.value = null;
      const response = await fuelRecordApi.getFuelRecords(params);
      fuelRecords.value = response.fuel_records;
      return response;
    } catch (err) {
      console.error("获取油耗记录列表失败:", err);
      error.value = "获取油耗记录列表失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchFuelRecord(recordId: number) {
    try {
      loading.value = true;
      error.value = null;
      const record = await fuelRecordApi.getFuelRecord(recordId);
      currentFuelRecord.value = record;
      return record;
    } catch (err) {
      console.error("获取油耗记录详情失败:", err);
      error.value = "获取油耗记录详情失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createFuelRecord(recordData: VehicleFuelRecordCreate) {
    try {
      loading.value = true;
      error.value = null;
      const newRecord = await fuelRecordApi.createFuelRecord(recordData);
      fuelRecords.value.unshift(newRecord.record);
      return newRecord;
    } catch (err) {
      console.error("创建油耗记录失败:", err);
      error.value = "创建油耗记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateFuelRecord(
    recordId: number,
    recordData: VehicleFuelRecordUpdate,
  ) {
    try {
      loading.value = true;
      error.value = null;
      const updatedRecord = await fuelRecordApi.updateFuelRecord(
        recordId,
        recordData,
      );
      const index = fuelRecords.value.findIndex((r) => r.id === recordId);
      if (index !== -1) {
        fuelRecords.value[index] = updatedRecord.record;
      }
      if (currentFuelRecord.value?.id === recordId) {
        currentFuelRecord.value = updatedRecord.record;
      }
      return updatedRecord;
    } catch (err) {
      console.error("更新油耗记录失败:", err);
      error.value = "更新油耗记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function deleteFuelRecord(recordId: number) {
    try {
      loading.value = true;
      error.value = null;
      await fuelRecordApi.deleteFuelRecord(recordId);
      fuelRecords.value = fuelRecords.value.filter((r) => r.id !== recordId);
      if (currentFuelRecord.value?.id === recordId) {
        currentFuelRecord.value = null;
      }
    } catch (err) {
      console.error("删除油耗记录失败:", err);
      error.value = "删除油耗记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchFuelRecordsByVehicle(
    vehicleId: number,
    params?: { skip?: number; limit?: number },
  ) {
    try {
      loading.value = true;
      error.value = null;
      const response = await fuelRecordApi.getFuelRecordsByVehicle(
        vehicleId,
        params,
      );
      return response;
    } catch (err) {
      console.error("获取车辆油耗记录失败:", err);
      error.value = "获取车辆油耗记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchLatestFuelRecord(vehicleId: number) {
    try {
      loading.value = true;
      error.value = null;
      const record = await fuelRecordApi.getLatestFuelRecord(vehicleId);
      return record;
    } catch (err) {
      console.error("获取最新油耗记录失败:", err);
      error.value = "获取最新油耗记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 统计方法
  async function fetchFuelStats(params?: FuelConsumptionStatsParams) {
    try {
      loading.value = true;
      error.value = null;
      const stats = await fuelStatsApi.getFuelConsumptionStats(params);
      fuelStats.value = stats;
      return stats;
    } catch (err) {
      console.error("获取油耗统计失败:", err);
      error.value = "获取油耗统计失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchFuelCostSummary(params?: {
    start_date?: string;
    end_date?: string;
    vehicle_id?: number;
  }) {
    try {
      loading.value = true;
      error.value = null;
      const summary = await fuelStatsApi.getFuelCostSummary(params);
      return summary;
    } catch (err) {
      console.error("获取油耗费用汇总失败:", err);
      error.value = "获取油耗费用汇总失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchGasStationTypes() {
    try {
      loading.value = true;
      error.value = null;
      const types = await fuelStatsApi.getGasStationTypes();
      return types;
    } catch (err) {
      console.error("获取加油站类型失败:", err);
      error.value = "获取加油站类型失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 清除错误
  function clearError() {
    error.value = null;
  }

  // 重置状态
  function reset() {
    vehicles.value = [];
    vehiclesWithStats.value = [];
    currentVehicle.value = null;
    fuelRecords.value = [];
    currentFuelRecord.value = null;
    fuelStats.value = null;
    error.value = null;
    loading.value = false;
  }

  return {
    // 车辆状态
    vehicles,
    vehiclesWithStats,
    currentVehicle,

    // 油耗记录状态
    fuelRecords,
    currentFuelRecord,

    // 统计状态
    fuelStats,

    // 通用状态
    loading,
    error,

    // 计算属性
    activeVehicles,
    vehicleCount,
    activeVehicleCount,
    totalFuelCost,
    totalFuelAmount,

    // 车辆管理方法
    fetchVehicles,
    fetchVehiclesWithStats,
    fetchVehicle,
    createVehicle,
    updateVehicle,
    deleteVehicle,

    // 油耗记录管理方法
    fetchFuelRecords,
    fetchFuelRecord,
    createFuelRecord,
    updateFuelRecord,
    deleteFuelRecord,
    fetchFuelRecordsByVehicle,
    fetchLatestFuelRecord,

    // 统计方法
    fetchFuelStats,
    fetchFuelCostSummary,
    fetchGasStationTypes,

    // 通用方法
    clearError,
    reset,
  };
});
